<template>
    <div class="login_container">
        <!--        title:左上角标题 v-model：对话框显示和隐藏-->
        <el-dialog v-model="useStore.visible" title="用户登录">
            <!--对话框身体结构-->
            <el-row>
                <!--  左侧-->
                <el-col :span="12">
                    <div class="login" v-show="scene==0">
                        <el-form :model="loginParam" :rules="rules" ref="form">
                            <el-form-item prop="phone">
                                <el-input placeholder="请你输入手机号码" :prefix-icon="User"
                                          v-model="loginParam.phone"/>
                            </el-form-item>
                            <el-form-item prop="code">
                                <el-input placeholder="请你输入手机验证码" :prefix-icon="Lock"
                                          v-model="loginParam.code"/>
                            </el-form-item>
                            <el-form-item>
                                <el-button :disabled="!isPhone || flag">
                                    <CountDown v-if="flag" :flag="flag" @getFlag='getFlag'/>
                                    <span @click="getCode" v-else>获取验证码</span>
                                </el-button>
                            </el-form-item>
                        </el-form>
                        <div class="bottom">
                            <el-button @click="login" :disabled="!isPhone||loginParam.code.length < 6"
                                       style="width: 100%;  " type="primary" size="default">用户登录
                            </el-button>
                            <p>微信扫码登录</p>
                            <svg @click="changeScene" t="1689068444656" class="icon" viewBox="0 0 1024 1024"
                                 version="1.1"
                                 xmlns="http://www.w3.org/2000/svg" p-id="2347" width="48" height="48">
                                <path d="M183.379592 699.559184c-4.179592 0-8.359184-1.044898-11.493878-3.657143-6.269388-4.702041-9.404082-12.016327-7.836734-19.330612l13.061224-77.322449C136.881633 553.273469 114.938776 496.326531 114.938776 437.289796 114.938776 292.571429 246.073469 175.020408 408.032653 175.020408c76.8 0 149.420408 26.644898 204.8 74.710204 55.379592 48.587755 86.726531 113.893878 88.293878 183.379592 0 5.746939-2.089796 10.971429-6.269388 14.628572s-9.404082 5.746939-15.151021 5.746938c-5.22449-0.522449-9.404082-0.522449-13.583673-0.522449-112.326531 0-203.232653 79.934694-203.232653 178.677551 0 13.583673 1.567347 27.167347 5.22449 40.751021 1.567347 5.746939 0.522449 11.493878-2.612245 16.195918-3.134694 4.702041-8.359184 7.836735-14.106123 8.881633-14.106122 2.089796-28.734694 3.134694-43.363265 3.134694-52.767347 0-104.489796-12.538776-149.420408-36.571429l-65.828572 34.481633c-3.134694 0-6.269388 1.044898-9.404081 1.044898z"
                                      fill="#0B9682" p-id="2348"></path>
                                <path d="M303.542857 352.653061m-35.004081 0a35.004082 35.004082 0 1 0 70.008163 0 35.004082 35.004082 0 1 0-70.008163 0Z"
                                      fill="#DCFFFA" p-id="2349"></path>
                                <path d="M512 352.653061m-35.004082 0a35.004082 35.004082 0 1 0 70.008164 0 35.004082 35.004082 0 1 0-70.008164 0Z"
                                      fill="#DCFFFA" p-id="2350"></path>
                                <path d="M849.502041 849.502041c-3.134694 0-6.269388-0.522449-9.404082-2.089796l-52.244898-27.167347c-37.093878 19.330612-78.889796 29.779592-122.253061 29.779592-134.269388 0-242.938776-98.220408-242.938776-218.383674S531.853061 412.734694 665.6 412.734694 909.061224 510.955102 909.061224 631.118367c0 48.065306-17.763265 95.085714-50.677551 133.22449l10.44898 61.64898c1.044898 7.314286-1.567347 15.15102-7.836735 19.330612-3.134694 3.134694-7.314286 4.179592-11.493877 4.179592z"
                                      fill="#16C4AF" p-id="2351"></path>
                                <path d="M576.261224 575.738776m-29.779591 0a29.779592 29.779592 0 1 0 59.559183 0 29.779592 29.779592 0 1 0-59.559183 0Z"
                                      fill="#DCFFFA" p-id="2352"></path>
                                <path d="M755.461224 575.738776m-29.779591 0a29.779592 29.779592 0 1 0 59.559183 0 29.779592 29.779592 0 1 0-59.559183 0Z"
                                      fill="#DCFFFA" p-id="2353"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="webChat" v-show="scene==1">
                        <!-- 扫码登陆的结构-->
                        <div id="login_container"></div>
                        <div class="phone" @click="handler">
                            <p>手机短信验证码登录</p>
                            <svg t="1689691506023" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                 xmlns="http://www.w3.org/2000/svg" p-id="2402" width="16" height="16">
                                <path d="M512 884.053333c-40.96 0-75.093333-34.133333-75.093333-75.093333s34.133333-75.093333 75.093333-75.093333 75.093333 34.133333 75.093333 75.093333S552.96 884.053333 512 884.053333zM512 771.413333c-20.48 0-37.546667 17.066667-37.546667 37.546667s17.066667 37.546667 37.546667 37.546667c20.48 0 37.546667-17.066667 37.546667-37.546667S532.48 771.413333 512 771.413333z"
                                      fill="#FF9000" p-id="2403"></path>
                                <path d="M679.253333 993.28c-3.413333 0-6.826667 0-10.24-3.413333-40.96-23.893333-109.226667-23.893333-109.226667-23.893333l0 0L276.48 965.973333c-54.613333 0-98.986667-44.373333-98.986667-98.986667L177.493333 139.946667c0-54.613333 44.373333-98.986667 98.986667-98.986667l471.04 0c54.613333 0 98.986667 44.373333 98.986667 98.986667l0 727.04c0 54.613333-44.373333 98.986667-98.986667 98.986667-10.24 0-17.066667-6.826667-17.066667-17.066667s6.826667-17.066667 17.066667-17.066667c34.133333 0 61.44-27.306667 61.44-61.44L808.96 139.946667c0-34.133333-27.306667-61.44-61.44-61.44L276.48 78.506667c-34.133333 0-61.44 27.306667-61.44 61.44l0 727.04c0 34.133333 27.306667 61.44 61.44 61.44l283.306667 0c3.413333 0 78.506667 0 126.293333 30.72 10.24 6.826667 10.24 17.066667 6.826667 23.893333C692.906667 989.866667 686.08 993.28 679.253333 993.28z"
                                      fill="#FF9000" p-id="2404"></path>
                                <path d="M590.506667 150.186667l-153.6 0c-10.24 0-17.066667-6.826667-17.066667-17.066667s6.826667-17.066667 17.066667-17.066667l153.6 0c10.24 0 17.066667 6.826667 17.066667 17.066667C607.573333 139.946667 600.746667 150.186667 590.506667 150.186667z"
                                      fill="#FF9000" p-id="2405"></path>
                            </svg>
                        </div>
                    </div>
                </el-col>
                <!--  右侧-->
                <el-col :span="12">
                    <div class="rightContent">
                        <div class="top">
                            <div class="item">
                                <img src="../../assets/images/code_app.png" alt="">
                                <svg t="1689069274451" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                     xmlns="http://www.w3.org/2000/svg" p-id="3069" width="16" height="16">
                                    <path d="M816.551274 248.167103C697.80273 131.500986 553.294498 97.66946 394.437467 140.52757 114.716718 215.994356 28.163433 506.98887 169.479973 696.646394c6.853082 9.198499 8.147564 26.164916 5.545296 38.09769-7.601118 34.868135-18.714224 68.958558-28.000728 103.474676-4.965082 18.455327-7.90504 37.21253 8.632611 52.019771 17.777899 15.921621 36.82572 12.654204 56.258305 2.777253 31.879058-16.200984 64.335261-31.314193 95.763041-48.336892 20.469194-11.086499 38.847773-11.658528 61.942771-5.240351 46.063105 12.799514 93.717452 19.872606 117.992321 24.74866 144.317896-2.603291 249.610988-41.736567 333.958024-129.489166C955.8826 594.966597 954.903296 384.090818 816.551274 248.167103zM763.498988 681.878039C658.864906 785.728268 531.49603 810.562886 393.782551 764.371868c-45.408189-15.229866-82.686211-19.207457-122.088616 7.493671-3.576455 2.423189-8.448416 2.934842-26.51284 8.852622 36.271088-62.917982 9.41851-102.273315-21.181415-146.894581-67.886133-98.989525-54.03773-226.624461 26.78197-318.740438 132.026966-150.480246 390.603139-150.382009 522.634198 0.196475C869.144096 424.455131 867.098507 579.054185 763.498988 681.878039z"
                                          p-id="3070"></path>
                                    <path d="M640.32976 377.432165c-26.245757-0.961908-47.457872 18.594497-48.955992 45.13906-1.532913 27.1565 16.636912 48.230468 43.304272 50.227961 26.571169 1.989307 48.850591-16.263405 51.568493-42.247196C689.112814 403.14478 667.75846 378.439098 640.32976 377.432165z"
                                          p-id="3071"></path>
                                    <path d="M385.221572 377.38714c-27.757181 0.205685-48.88743 23.684422-46.821375 52.023864 1.940189 26.610054 23.154349 44.910862 50.212612 43.317575 26.505677-1.560542 46.149063-22.886243 45.152363-49.02046C432.798147 398.345474 410.636405 377.198851 385.221572 377.38714z"
                                          p-id="3072"></path>
                                </svg>
                                <p>微信扫一扫关注</p>
                                <p>“快速预约挂号”</p>
                            </div>
                            <div class="item">
                                <img src="../../assets/images/code_login_wechat.png" alt="">
                                <svg t="1689069374075" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                     xmlns="http://www.w3.org/2000/svg" p-id="4848" width="16" height="16">
                                    <path d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                                          p-id="4849"></path>
                                </svg>
                                <p>扫一扫下载</p>
                                <p>“预约挂号”app</p>
                            </div>
                        </div>
                    </div>
                    <p class="tip">尚医通官方指定平台</p>
                    <p class="tip">快速挂号 安全方心</p>
                </el-col>
            </el-row>
            <!-- 底部插槽-->
            <template #footer>
                <el-button @click="closeIndexInFooter" type="primary" size="default">关闭窗口</el-button>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
//获取user仓库的数据（visible）
import useUserStore from "@/store/modules/user.ts";
import {Lock, User} from "@element-plus/icons-vue";
import {computed, reactive, ref, watch} from "vue";
//映入倒计时组件
import CountDown from '@/components/count_down/index.vue'
import {ElMessage, FormRules} from "element-plus";
import {reqWxLogin} from "@/api/hospital";
import {WXLoginResponseData} from "@/api/hospital/type.ts";
import {useRoute, useRouter} from "vue-router";
//定义一个响应式数据控制倒计时的显示与隐藏
let flag = ref<boolean>(false)
let $route = useRoute()
let $router = useRouter()
let useStore = useUserStore()
let scene = ref<number>(0)//代表收集号码登录   1：微信扫码  0：账号登录

//获取表单实例
let form = ref<any>()
//收集表单数据 ----手机号码
let loginParam = reactive({
    phone: '',
    code: ''
})
// 计算出当前表单元素收集的内容是否是手机格式
let isPhone = computed(() => {
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
    return reg.test(loginParam.phone)
})

//点击微信小图标，切换为微信扫码登录
const changeScene = async () => {
    scene.value = 1

    //向服务器发请求获取微信扫码需要的参数
    //需要携带一个参数:用户授权成功之后的重定向到项目的页面地址
    let redirect_url = encodeURIComponent(window.location.origin + '/wxlogin')

    let result: WXLoginResponseData = await reqWxLogin(redirect_url)

    //生成微信扫码登录的二维码页面
    new WxLogin({
        self_redirect: true,//true：手机点击确认登录后可以在 iframe 内跳转到 redirect_uri，false：手机点击确认登录后可以在 top window 跳转到 redirect_uri。默认为 false。
        id: "login_container",//第三方页面显示二维码的容器id
        appid: result.data.appid,//应用唯一标识，在微信开放平台提交应用审核通过后获得
        scope: "snsapi_login",//应用授权作用域，拥有多个作用域用逗号（,）分隔，网页应用目前仅填写snsapi_login即可
        redirect_uri: result.data.redirectUri,//重定向地址，需要进行UrlEncode
        state: result.data.state,//用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
        style: "black",//提供"black"、"white"可选，默认为黑色文字描述。
        href: ""//自定义样式链接，第三方可根据实际需求覆盖默认样式。详见文档底部FAQ
    });
}

//获取验证码的回调
const getCode = async () => {
    //避免未输入手机号时还能点击
    //手机号校验失败，不可以点击，或者，出现倒计时，不可以点
    if (!isPhone.value || flag.value) return;
    //开启倒计时模式
    flag.value = true
    //通知pinia仓库存储验证码
    try {
        //获取验证码成功
        await useStore.getCode(loginParam.phone)
        loginParam.code = useStore.code
    } catch (error) {
        //获取验证码失败
        ElMessage({
            type: "error",
            message: error.message
        })
    }
}

//计数组件的自定义事件
const getFlag = (val: boolean) => {
    flag.value = val
}

//点击用户登录按钮的回调
const login = async () => {

    //保证表单的两项都符合条件
    await form.value.validate()
    //发送登录请求
    //登录请求成功：顶部组件需要展示用户名字，对话框关闭
    //失败，弹出对应登陆失败的错误信息
    try {
        //用户登陆成功
        await useStore.userLogin(loginParam)
        //关闭对话框
        useStore.visible = false
        //获取url的query参数
        let redirect = $route.query.redirect
        if (redirect) {
            await $router.push(redirect as string)
        } else {
            await $router.push('/home')
        }
    } catch (error) {
        //获取验证码失败
        ElMessage({
            type: "error",
            message: error.message
        })
    }
}

//自定义手机号码的验证函数
const validatePhone = (rule: any, value: any, callback: any) => {
    //rule:即为表单校验规则对象
    //value:即为当前文本内容
    //callBack：回调函数
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
    if (reg.test(value)) {
        callback();
    } else {
        callback(new Error(('请输入正确的手机号码格式')));
    }
}

const validateCode = (rule: any, value: any, callback: any) => {
    //rule:即为表单校验规则对象
    //value:即为当前文本内容
    //callBack：回调函数
    const reg = /^\d{6}$/
    if (reg.test(value)) {
        callback();
    } else {
        callback(new Error(('请输入正确的验证码')));
    }
}

//表单校验的规则对象
const rules = reactive<FormRules<typeof loginParam>>({
    //手机号码的校验规则
    //trigger:表单校验时机 change：文本改变时校验  blur：失去焦点时触发校验
    // phone:[
    //     {required:true,message:'请输入正确的手机号码',trigger:"change"},
    //     {}
    // ],
    // code:[
    //     {required:true,message:'请输入正确的验证码',trigger:blur},
    //
    // ]
    phone: [{validator: validatePhone, trigger: 'change'}],
    code: [{validator: validateCode, trigger: 'blur'}],

})

//对话框关闭事件的回调
// const closeIndex = ()=>{
//     //清空收集的数据
//     Object.assign(loginParam,{phone:'',code:''})
//     //清除表单的上一次校验的结果
//     form.value.resetFields();
// }
const closeIndexInFooter = () => {
    useStore.visible = false
    // //清空收集的数据
    // Object.assign(loginParam,{phone:'',code:''})
    // //清除表单的上一次校验的结果
    // form.value.resetFields();
}

//点击手机短信验证码盒子的回调
const handler = () => {
    scene.value = 0
}

//监听场景的数值
watch(() => scene.value, (val: number) => {
    if (val == 1) {
        useStore.queryState()
    }
})

</script>

<script lang="ts">
export default {
    name: 'Login'
}
</script>


<style scoped lang="scss">
.login_container {
  ::v-deep(.el-dialog__body) {
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
  }

  .login {
    padding: 20px;
    border: 1px solid #ccc;

    .bottom {
      display: flex;
      flex-direction: column;
      align-items: center;
    }


  }

  .webChat {
    display: flex;
    flex-direction: column;
    align-items: center;

    .phone {
      display: flex;
      flex-direction: column;
      align-items: center;

      p {
        margin-top: 0;
      }
    }
  }

  .rightContent {
    .top {
      display: flex;
      justify-content: space-around;

      .item {
        display: flex;
        flex-direction: column;
        align-items: center;

        img {
          width: 130px;
          height: 130px;
        }

        p {
          margin: 5px 0;
        }
      }
    }

  }

  .tip {
    text-align: center;
    margin: 20px 0;
    font-weight: 380;
    font-size: 20px;
  }


}

</style>